<template>
  <!-- 面包屑导航 -->
  <el-breadcrumb separator-class="el-icon-arrow-right">
    <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
    <el-breadcrumb-item>文件管理</el-breadcrumb-item>
    <el-breadcrumb-item>我的文件</el-breadcrumb-item>
  </el-breadcrumb>

  <!-- 内容区域 -->
  <el-card class="box-card">
    <!-- 搜索条件 -->
    <el-row :gutter="20">
      <el-col :span="8">
        <el-input placeholder="请输入用户名" v-model="queryParams.titleName">
          <template #append>
            <el-button icon="Search" @click="search(1)"/>
          </template>
        </el-input>
      </el-col>
      <el-col :span="4">
        <el-button type="info" @click="clearSearch">清空</el-button>
        <el-button type="primary" @click="searchComments">搜索</el-button>
      </el-col>
    </el-row>

    <el-table :data="fileList" stripe>
      <el-table-column label="序号" type="index" width="100"></el-table-column>
      <el-table-column prop="titleName" label="文件名" width="150"></el-table-column>
      <el-table-column prop="sort" label="文件大小"></el-table-column>
      <el-table-column prop="createTime" label="创建时间"></el-table-column>
      <el-table-column label="操作" width="200">
        <template v-slot="scope">
          <el-button type="primary" icon="el-icon-edit" size="small"
                     @click="handleEditDialogShow(scope.row.id)">恢复
          </el-button>
          <el-button type="danger" icon="el-icon-delete" size="small"
                     @click="deleteBlog(scope.row.id)">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <el-pagination background layout="total, sizes, prev, pager, next, jumper" :total="total"
                   :current-page="queryParams.pageNum" :page-sizes="[1, 5, 10]" :page-size="queryParams.pageSize"
                   @size-change="handleSizeChange" @current-change="handlePageChange"/>
  </el-card>

  <!-- 编辑博客的对话框 -->
  <el-dialog title="编辑博客" v-model="editDialogVisible" width="70%" @close="handleEditDialogClose">
    <el-form :model="editForm" ref="editFormRef" label-width="80px" status-icon>
      <el-form-item label="标题" prop="titleName">
        <el-input v-model="editForm.titleName"/>
      </el-form-item>
      <el-form-item label="作者" prop="author">
        <el-input v-model="editForm.author"/>
      </el-form-item>
      <el-form-item label="分类" prop="sort">
        <el-input v-model="editForm.sort"/>
      </el-form-item>
      <el-form-item label="内容" prop="content">
        <el-input type="textarea" v-model="editForm.content"/>
      </el-form-item>
      <!-- 使用栅格系统布局图片封面和发布时间 -->

      <el-form-item label="图片" prop="image">
        <el-upload class="upload-demo" :show-file-list="false" :limit="1" accept="image/*"
                   :on-change="handleImageChange">
          <el-button size="small" type="primary">点击上传</el-button>
        </el-upload>
        <div v-if="editForm.imageFile" class="image-preview">
          <img :src="editForm.imageUrl" width="60%"/>
        </div>
        <img v-else :src="editForm.imageUrl" width="60%"/>
      </el-form-item>

    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="updateBlog">确 定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import {inject, ref} from 'vue';
import axios from '@admin/utils/request.js';
// 注入全局属性
let $message = inject('$message');
let $confirm = inject('$confirm');

/* 1: 查询博客 */
// 查询参数
const queryParams = ref({
  titleName: '',
  pageNum: 1,
  pageSize: 5
});
let pageInfo = ref({});
let id = ref([]);

// 查询结果
const fileList = ref([]);
const total = ref(0);

// 获取博客列表
const search = function (pageNum) {
  if (pageNum) {
    queryParams.value.pageNum = pageNum;
  }
  axios.post('/blog/search', queryParams.value)
      .then(response => {
        id.value = [];
        pageInfo.value = response;
        blogList.value = pageInfo.value.list;
        total.value = pageInfo.value.total;
        queryParams.value.pageNum = pageInfo.value.pageNum;
      }).catch(error => {
    console.log(error);
  });
};

/* 2: 分页 */
const handleSizeChange = function (newPageSize) {
  queryParams.value.pageSize = newPageSize;
  search(1);
};
const handlePageChange = function (newPageNum) {
  search(newPageNum);
};

/* 4: 删除博客 */
const deleteBlog = async function (id) {
  try {
    await $confirm('此操作将永久删除该博客, 是否继续?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });
  } catch (error) {
    return;
  }

  axios.post(`blog/delete/${id}`,)
      .then(() => {
        $message.success('删除成功');
        search(); // 重新搜索以更新表格
      }).catch((error) => {
    $message.fail(error.data.msg || '删除失败');
  });
};

// 处理图片预览
const handleImageChange = (file) => {
  editForm.value.imageFile = file.raw
  const reader = new FileReader();
  reader.onload = (e) => {
    editForm.value.imageUrl = e.target.result; // 更新图片 URL
  };
  reader.readAsDataURL(file.raw); // 获取图片的 Data URL
};

/* 5: 编辑博客 */
const editDialogVisible = ref(false);
const editForm = ref({});
const editFormRef = ref();

const handleEditDialogClose = function () {
  editFormRef.value.resetFields();
};

const handleEditDialogShow = async function (id) {
  axios.get('blog/Get?id=' + id)
      .then(response => {
        editDialogVisible.value = true;
        editForm.value = response.data.data;
        if (editForm.value.filePath) {
          axios.get({
            url: '/images?fileName=' + editForm.value.fileName,
            responseType: 'blob'
          }).then(imageResponse => {
            const imageUrl = URL.createObjectURL(imageResponse.data); // 创建图片 URL
            editForm.value.imageUrl = imageUrl; // 将生成的 URL 存入 editForm
          }).catch(error => {
            $message.fail(error.data.msg || '获取图片失败');
          });
        }
      }).catch(error => {
    $message.fail(error.data.msg);
  });
};

const updateBlog = function () {
  editFormRef.value.validate(async valid => {
    if (!valid) return;
    const formData = new FormData();
    let blob = new Blob([JSON.stringify(editForm.value)], {
      type: 'application/json'
    });
    formData.append('json', blob);
    // 添加文件
    if (editForm.value.imageFile) {
      formData.append('file', editForm.value.imageFile);
    }
    axios.post('/blog/update', formData,)
        .then(() => {
          $message.success('修改成功')
          editDialogVisible.value = false;
          search();
        }).catch(() => {
      $message.fail('修改失败')
      editDialogVisible.value = false;
      search();
    });
  });
};

search()

</script>

<style scoped>
.box-card {
  margin-top: 20px;
}

.image-preview {
  margin-top: ¼em;
}
</style>

<style scoped>
.box-card {
  margin-top: 20px;
}
</style>